package com.syezon.wifikey.location;

import android.arch.lifecycle.MutableLiveData;
import android.content.Context;
import android.text.TextUtils;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.syezon.wifikey.utils.Utils;

public class LocationService implements BDLocationListener {

    private static final String TAG = LocationService.class.getSimpleName();

    private static LocationService mLocationService;
    private Context mContext;
    private LocationClient mLocationClient;
    private LocationClientOption mOption;
    private MutableLiveData<LocationInfo> mLocationLiveData = new MutableLiveData<>();

    private LocationService(Context context) {
        this.mContext = context;
        mLocationClient = new LocationClient(context);
        mLocationClient.setLocOption(getDefaultLocationClientOption());
        mLocationClient.registerLocationListener(this);
    }

    public static LocationService getInstance() {
        if (mLocationService == null) {
            synchronized (LocationService.class) {
                if (mLocationService == null) {
                    mLocationService = new LocationService(Utils.getApp());
                }
            }
        }
        return mLocationService;
    }

    public MutableLiveData<LocationInfo> getLocationLiveData() {
        return mLocationLiveData;
    }

    public synchronized void getLocation() {
        mLocationClient.start();
    }


    /***
     *
     * @return DefaultLocationClientOption
     */
    public LocationClientOption getDefaultLocationClientOption() {
        if (mOption == null) {
            mOption = new LocationClientOption();
            mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
            mOption.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
            mOption.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
            mOption.setNeedDeviceDirect(false);//可选，设置是否需要设备方向结果
            mOption.setLocationNotify(false);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
            mOption.setIgnoreKillProcess(true);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
            mOption.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        }
        return mOption;
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        try {
            LocationInfo locationInfo = new LocationInfo();
            String location = bdLocation.getAddrStr();
            if (!TextUtils.isEmpty(location)) {
                locationInfo.setAddress(location);
            } else {
                locationInfo.setAddress("");
            }
            mLocationLiveData.postValue(locationInfo);
        } catch (Exception e) {

        }

    }
}
